package cn.cxl.cxlutils;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.cxl.cxlutils.utils.MyLog;
import cn.cxl.cxlutils.utils.NetworkUtils;
import cn.cxl.cxlutils.widget.CustomView;
import cn.cxl.cxlutils.widget.MyView;
import io.flutter.embedding.android.FlutterActivity;


public class VideoActivity extends AppCompatActivity implements SurfaceHolder.Callback {
    private final String TAG = "AppCompatActivity";
    private static final int FRONT = Camera.CameraInfo.CAMERA_FACING_FRONT;//前置摄像头标记
    private static final int BACK = Camera.CameraInfo.CAMERA_FACING_BACK;//后置摄像头标记
    private Camera mCamera;
    private Camera.Parameters myParameters;
    private boolean isView = false;
    private SurfaceHolder mSurfaceHolder;
    private SurfaceHolder holder;
    private boolean mStartedFlg = false;
    private MediaRecorder mRecorder;
    private int cameraID;
    private boolean isRecord = false;
    private String time = "00:00";

    /**
     * 6.0权限处理
     **/
    private boolean bPermission = false;
    private final int WRITE_PERMISSION_REQ_CODE = 100;
    private SurfaceView mSurfaceView;
    private TextView mReplace;
    private TextView mVideo;
    private TextView mCameraTime;
    private CameraThread cameraThread;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("MyService", "onServiceConnected");

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("MyService", "onServiceDisconnected");

        }
    };

    private boolean checkPublishPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(VideoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(VideoActivity.this, Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(VideoActivity.this, Manifest.permission.RECORD_AUDIO)) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(VideoActivity.this,
                        (String[]) permissions.toArray(new String[0]),
                        WRITE_PERMISSION_REQ_CODE);
                return false;
            }
        }
        return true;

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case WRITE_PERMISSION_REQ_CODE:
                for (int ret : grantResults) {
                    if (ret != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                }
                bPermission = true;
                break;
            default:
                break;
        }
    }

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initScreen();
        setContentView(R.layout.activity_video);
        cameraID = BACK;
        bPermission = checkPublishPermission();
        mSurfaceView = findViewById(R.id.surfaceView);
        mReplace = findViewById(R.id.replace);
        mVideo = findViewById(R.id.video);
        mCameraTime = findViewById(R.id.cmeraTime);
        cameraThread = new CameraThread(mCameraTime);
//        if (bPermission) {
//            OpenCamera();
//        } else {
//            Toast.makeText(this, "没有权限", Toast.LENGTH_SHORT).show();
//        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            RoadRecordService.start(this);
        }
//        MyService.Companion.start(this);
//        MyService.Companion.bind(this,connection);
//        mSurfaceView.setKeepScreenOn(true);
    }

    public void OpenCamera() {
        holder = mSurfaceView.getHolder();// 取得holder

        holder.addCallback(VideoActivity.this); // holder加入回调接口


        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }


    /*初始化相机*/
    public void initCamera() {
        if (mCamera == null && !isView) {
            mCamera = Camera.open(cameraID);
            Log.i(TAG, "camera.open()");
        }

        if (mCamera != null && !isView) {
            try {
                myParameters = mCamera.getParameters();
                myParameters.setPreviewSize(1920, 1080);
                myParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                mCamera.setParameters(myParameters);
                mCamera.setPreviewDisplay(mSurfaceHolder);
                mCamera.setDisplayOrientation(90);
                mCamera.startPreview();
                isView = true;
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                Log.i(TAG, "初始化相机错误");
            }
        }
    }

    /**
     * 获取系统时间，保存文件以系统时间戳命名
     */
    public String getDate() {
        Calendar ca = Calendar.getInstance();
        int year = ca.get(Calendar.YEAR);
        int month = ca.get(Calendar.MONTH);
        int day = ca.get(Calendar.DATE);
        int minute = ca.get(Calendar.MINUTE);
        int hour = ca.get(Calendar.HOUR);
        int second = ca.get(Calendar.SECOND);

        String date = "" + year + (month + 1) + day + hour + minute + second;
        Log.d(TAG, "date:" + date);

        return date;
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        // TODO Auto-generated method stub
        mSurfaceHolder = holder;
        initCamera();
        mVideo.setOnClickListener(new View.OnClickListener() {

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startRecode(mCamera);
            }
        });

        mReplace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (isRecord) {
                        Toast.makeText(VideoActivity.this, "视频录制中，不允许调转摄像头", Toast.LENGTH_SHORT).show();
                    } else {
                        changeCamera();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    isRecord = false;
                    cameraThread.stop();
                    Log.i(TAG, "切换相机错误");
                }
            }
        });


    }

    public void startRecode(Camera mCamera) {
        isRecord = true;
        if (!mStartedFlg) {
            // Start
            if (mRecorder == null) {
                mRecorder = new MediaRecorder(); // Create MediaRecorder
            }
            try {
                mCamera.unlock();
                mRecorder.setCamera(mCamera);
                // Set audio and video source and encoder
                // 这两项需要放在setOutputFormat之前
                mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
                mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
                mRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_1080P));
                // Set output file path
                String path = getSDPath();
                if (path != null) {
                    File dir = new File(path + "/dlysc");
                    Log.i(TAG, (dir.exists()) + "");
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                    path = dir + "/" + getDate() + ".mp4";
                    mRecorder.setOutputFile(path);
                    if (cameraID == FRONT) {
                        mRecorder.setOrientationHint(90 + 180);
                    }
                    mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
                    Log.d(TAG, "bf mRecorder.prepare()");
                    mRecorder.prepare();
                    Log.d(TAG, "af mRecorder.prepare()");
                    Log.d(TAG, "bf mRecorder.start()");
                    mRecorder.start();   // Recording is now started
                    Log.d(TAG, "af mRecorder.start()");
                    cameraThread.start();
                    mStartedFlg = true;
                    mVideo.setText("停止");
                    Log.i(TAG, path);
                }
            } catch (Exception e) {
                e.printStackTrace();
                releaseMediaRecorder();
            }
        } else {
            // stop
            if (mStartedFlg) {
                try {
                    stopCamera();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mStartedFlg = false;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
// TODO Auto-generated method stub
        mSurfaceHolder = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    /**
     * 获取SD path
     */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
            return sdDir.toString();
        }
        return null;
    }

    //初始化屏幕设置
    public void initScreen() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        // 选择支持半透明模式,在有surfaceview的activity中使用。
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
    }


    public void stopCamera() {
        mCamera.lock();
        mRecorder.stop();
        mRecorder.reset();
        mVideo.setText("开始");

        isRecord = false;
        cameraThread.stop();
    }


    private void changeCamera() throws IOException {
        mCamera.stopPreview();
        mCamera.release();
        if (cameraID == FRONT) {
            cameraID = BACK;
            mCamera = Camera.open(BACK);
        } else if (cameraID == BACK) {
            cameraID = FRONT;
            mCamera = Camera.open(FRONT);
            mSurfaceView.setRotation(180);
        }
        mCamera.setDisplayOrientation(90);
        mCamera.setPreviewDisplay(mSurfaceHolder);
        mCamera.startPreview();
    }

    @Override
    protected void onPause() {
        Log.i(TAG, "后台1");
        super.onPause();
//        isRecord = false;
//        cameraThread.stop();
//        releaseMediaRecorder();
//        releaseCamera();

    }

    @Override
    protected void onRestart() {
        Log.i(TAG, "后台2");
        super.onRestart();
    }

    @Override
    protected void onResume() {
        Log.i(TAG, "后台3");
//        OpenCamera();
//        if (mCamera != null){
//            mCamera.stopPreview();
//            mCamera.release();
//
//            cameraID = BACK;
//            mCamera = Camera.open(BACK);
//            mCamera.setDisplayOrientation(90);
//            try {
//                mCamera.setPreviewDisplay(mSurfaceHolder);
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//            mCamera.startPreview();
//
//
//        }
        super.onResume();
    }

    @Override
    protected void onStart() {
        Log.i(TAG, "后台4");
        super.onStart();
    }

    private void releaseMediaRecorder() {
        if (mRecorder != null) {
            mRecorder.reset();   // clear recorder configuration
            mRecorder.release(); // release the recorder object
            mRecorder = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }

    public class CameraThread extends Thread {
        private TextView textView;

        public CameraThread(TextView textView) {
            this.textView = textView;
        }

        @Override
        public void run() {
            int second = 0;
            int minute = 0;
            while (isRecord) {

                if (second > 10) {
                    time = "0" + minute + ":" + second;
                } else {
                    time = "0" + minute + ":" + "0" + second;

                }
                second++;
                if (second == 60) {
                    minute++;
                    second = 0;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText(time);
                    }
                });
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
